Frequency Counting
Tags: #◇Computer Science #◇CCDSALG #◇Frequency Counting #◇Code Snippets #◇M1
◇Overview
Frequency counting measures the number of statements or steps an algorithm takes to complete a task. It's a method for analyzing an algorithm a priori.
RAM Model Assumptions
This theoretical analysis relies on the Random-Access Machine (RAM) model:
- Algorithms are computer programs running on a generic, single-processor RAM model.
- Instructions execute sequentially one at a time (no concurrent operations).
- Each basic instruction or data access takes a constant amount of time.
- The RAM model contains standard instructions typical of real computers.
◇Important Formulas
When determining the frequency count of an algorithm, different programming constructs are evaluated based on their basic operations:
1. Assignment Statements
- Count: for each statement.
2. Conditional Statements
- Evaluated as:
- The condition evaluation takes unit. Then, we assume the worst-case scenario by taking the maximum count between the
ifandelsebranches.
3. For Loops
For a loop like for j = lb to ub (where is the lower bound and is the upper bound):
- The loop header/condition evaluation:
- The statements inside the loop body:
4. While Loops
For a block like:
x = lb
while x <= ub:
...
- Initialization:
- The
whilecondition evaluation: - The statements inside the loop body:
(If the condition is strictly less than< ub, the condition is and body is .)
5. Do-While Loops
For a block like:
x = lb
do:
...
while x <= ub
- Initialization:
- The statements inside the loop body:
- The
whilecondition evaluation:
◇Worked Examples
Example 1: Conditional Block
if choice == "S" // 1
read(side) // 1
area = side * side // 1 (if block total = 2)
else
read(base) // 1
read(height) // 1
area = (base * height) / 2.0 // 1 (else block total = 3)
Total = .
Example 2: Simple For Loop
for j = 1 to 4 // (4 - 1) + 2 = 5
print(j) // (4 - 1) + 1 = 4
Total = .
Example 3: Nested For Loops
for j = 1 to n // n + 1
for k = 1 to n // n * (n + 1) = n^2 + n
print(j, k) // n * (n) = n^2
For the inner loop, it runs for k = 1 to n which is times, but since it is inside for j = 1 to n which loops times, its frequency is multiplied by .
Total sum = .
◇References & Navigation
- Related Notes: ◇Frequency Counting